import {
  Injectable,
  ConflictException,
  UnauthorizedException,
} from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';
import { LoginVO } from './vo/login.vo';
import { UserVO } from '../users/vo/user.vo';
@Injectable()
export class AuthService {
  constructor(
    private readonly usersService: UsersService,
    private readonly jwtService: JwtService,
  ) {}

  // 注册
  async register(data: RegisterDto) {
    const { username, password, nickname } = data;
    const exist = await this.usersService.findByUsername(username);
    if (exist) throw new ConflictException('用户名已存在');
    const hash = await bcrypt.hash(password, 10);
    const user = await this.usersService.createUser({
      username,
      password: hash,
      nickname,
    });
    const payload = { id: user.id, username: user.username };
    const token = this.jwtService.sign(payload);
    return new LoginVO({
      token,
      user: new UserVO(user),
    });
  }

  // 登录
  async login(data: LoginDto) {
    const { username, password } = data;
    const user = await this.usersService.findByUsername(username);
    if (!user) throw new UnauthorizedException('用户名或密码错误');
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) throw new UnauthorizedException('用户名或密码错误');
    const payload = { id: user.id, username: user.username };
    const token = this.jwtService.sign(payload);
    return new LoginVO({
      token,
      user: new UserVO(user),
    });
  }
}
